package br.org.etec.dotcao.mailer;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class MailerExecutor {

	private Sender sender;
	private Set<Receiver> receivers;
	private String subject;
	private String fileContent;
	private String charset;
	private Receiver replyTo;
	private int numberOfThreads;
	
	
	public void execute() throws Exception{
		if(numberOfThreads == 0){
			numberOfThreads = 1;
		}
		
		ExecutorService threadPool = Executors.newFixedThreadPool(numberOfThreads);
		CompletionService<Long> pool = new ExecutorCompletionService<Long>(threadPool);
		
		int receiversPerThread = (int) Math.ceil(receivers.size()/numberOfThreads);
		List<Receiver> helper = new ArrayList<Receiver>(this.receivers);
		
		for(int i = 0; i < numberOfThreads; i++){
			
			int start = i * receiversPerThread;
			int end = start + receiversPerThread;
			
			if(end >helper.size()){
				end = helper.size();
			}
			
			Set<Receiver> receivers = new HashSet<Receiver>(helper.subList(start, end));
			MailerTask task = new MailerTask(sender, receivers, subject, fileContent, charset, replyTo);
			pool.submit(task);
		}
		
		long success = 0;

		for(int i = 0; i < numberOfThreads; i++){
			success += pool.take().get();
		}
		
		threadPool.shutdown();
		
		System.out.println("Processo terminado... taxa de sucesso: " + success + "/" + receivers.size());
		System.out.println("Para mais detalhes consulte o log mailer-log.log");
	}

	public void setNumberOfThreads(int numberOfThreads) {
		this.numberOfThreads = numberOfThreads;
	}

	public void setSender(Sender sender) {
		this.sender = sender;
	}

	public void setReceivers(Set<Receiver> receivers) {
		this.receivers = receivers;
	}
	
	public void setReceiver(Receiver receiver) {
		this.receivers = new HashSet<Receiver>();
		receivers.add(receiver);
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public void setFileContent(String fileContent) {
		this.fileContent = fileContent;
	}

	public void setCharset(String charset) {
		this.charset = charset;
	}

	public void setReplyTo(Receiver replyTo) {
		this.replyTo = replyTo;
	}

}
